package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchantMapper merchantMapper;
    @Override
    public Result<UserLoginVO> login(UserLoginDTO dto) {

//      1.调用微信接口换取openid
        String openId = getOpenId(dto.getCode());
        if(StringUtils.isEmpty(openId)){
            throw new UserNotLoginException("用户登录失败");
        }
//      2.查询openid是否存在，如果是新用户，需要实现注册功能
        User user = userMapper.selectByOpenId(openId);
        if(user==null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            //入库
            userMapper.save(user);
        }
//      3.自义定token信息，返回给前端
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //4.查询商家信息
        Merchant merchant = merchantMapper.selectById(1l);
        //5.配送费计算
        String shopLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(shopLocation, dto.getLocation());
        //构建返回信息
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(openId)
                .shopAddress(merchant.getShopAddress())
                .shopId(merchant.getId())
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .id(user.getId())
                .deliveryFee(delivoryCost)
                .build();
        return Result.success(userLoginVO);
    }
    /**
     * 获取openid
     * @param code
     * @return
     */
    private String getOpenId(String code) {
        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("appid",weChatProperties.getAppid());
        paramsMap.put("secret",weChatProperties.getSecret());
        paramsMap.put("js_code",code);
        paramsMap.put("grant_type","authorization_code");

        String resJson = HttpClientUtil.doGet(WX_LOGIN_URL, paramsMap);

        //解析
        Map map = JSON.parseObject(resJson, Map.class);

        return map.get("openid").toString();
    }

}
